package com.dede.viewpagertest

import android.os.Bundle
import android.support.design.widget.BottomNavigationView
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_1 -> {
                view_pager.currentItem = 0
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_2 -> {
                view_pager.currentItem = 1
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_3 -> {
                view_pager.currentItem = 2
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_4 -> {
                view_pager.currentItem = 3
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_5 -> {
                view_pager.currentItem = 4
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

        view_pager.adapter = ParentAdapter(supportFragmentManager)
        view_pager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                navigation.selectedItemId = when (position) {
                    1 -> R.id.navigation_2
                    2 -> R.id.navigation_3
                    3 -> R.id.navigation_4
                    4 -> R.id.navigation_5
                    else -> R.id.navigation_1
                }

            }
        })
    }

    inner class ParentAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

        override fun getItem(position: Int): Fragment {
            return when (position) {
                1 -> ChildViewPagerFragment()
                else -> EmptyFragment()
            }
        }

        override fun getCount(): Int = navigation.maxItemCount

    }
}
